<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    <!-- <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>

    <script>
        /*
         Access to XMLHttpRequest at 'https://suggest.taobao.com/sug?code=utf-8&q=123&_ksTS=1640761010428_285&callback=jsonp286&k=1&area=c2c&bucketid=0' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
suggest.taobao.com/sug?code=utf-8&q=123&_ksTS=1640761010428_285&callback=jsonp286&k=1&area=c2c&bucketid=0:1 Failed to load resource: net::ERR_FAILED
        */
        // 解决跨域？
        // jsonp 就是使用<script>标签
        $.ajax({
            dataType:"jsonp",
            url: 'https://suggest.taobao.com/sug?code=utf-8&q=123&_ksTS=1640761010428_285&callback=jsonp286&k=1&area=c2c&bucketid=0',
            success: function(data) {
                // 
                console.log(data)
            }
        })
    </script> -->
    <!-- <script>
        // 这个函数必须为 全局函数
        function myjsonp(data) {
            console.log(data)
        }
    </script>
    <script src="https://suggest.taobao.com/sug?code=utf-8&q=123&_ksTS=1640761010428_285&callback=myjsonp&k=1&area=c2c&bucketid=0"></script>
 -->
    <script>
        function jsonp(url,keyword, fn) {
            // 1. 创建script标签
            var script = document.createElement("script");

            const strName = "jsonp" + parseInt(Math.random()*900 + 100);
            window[strName] = function(data){
                document.body.removeChild(script)
                fn(data)
            }

            
            script.src = url + keyword + "&callback=" + strName
            // 2. 加入body
            document.body.appendChild(script)
        }

        jsonp("https://suggest.taobao.com/sug?code=utf-8&_ksTS=1640761010428_285&k=1&area=c2c&bucketid=0&q=", "123", function(data) {
            console.log(data)
        })
    </script>
</body>
</html>